﻿Public Class usuarios
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        Try
            If Session("usuarioId") Is Nothing Then
                Response.Redirect("loguin.aspx")
            End If
            If Not Session("profesionId") Is Nothing Then
                If Permisos.Validar(Session("profesionId").ToString, 1) = False Then
                    Response.Redirect("Denied.aspx")
                End If
            Else
                Response.Redirect("Denied.aspx")
            End If
            If Not IsPostBack Then
                lbprofesion.Text = Session("profesion").ToString()
                lbnombre.Text = Session("nombre").ToString()
                cargacombos()
            End If
        Catch ex As Exception
            Response.Write(ex.Message)
        End Try
    End Sub

    Private Sub cargacombos()
        Try
            Dim docmd As New Sql_Server
            docmd.Conectar()
            docmd.Combo = cboprofesiones
            docmd.Listar_Combo("select * from profesiones order by profesion")
            docmd.Combo = cbodepartamentos
            docmd.Listar_Combo("select * from departamentos order by departamento")
            docmd.Desconectar()
        Catch ex As Exception

        End Try
    End Sub
    Protected Sub cbodepartamentos_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles cbodepartamentos.SelectedIndexChanged
        Dim docmd As New Sql_Server
        docmd.Conectar()
        docmd.Combo = cbociudad
        docmd.Listar_Combo("select * from ciudades where dptoCod=" & cbodepartamentos.SelectedValue & " order by ciudad")
        docmd.Desconectar()

    End Sub
    Protected Sub btnGuardar_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGuardar.Click
        If Page.IsValid = True Then
            Dim modelo As New DataClasses1DataContext()
            Dim Clausuarios As New usuario
            If IsNumeric(usuarioId.Value) Then
                'esta editando
                Dim EditaUsuario = (From u In modelo.usuarios Where u.usuarioId.Equals(usuarioId.Value) Select u).Single()
                EditaUsuario.usuario = usuario.Text
                EditaUsuario.nombre = nombre.Text
                EditaUsuario.documento = documento.Text
                EditaUsuario.celular = celular.Text
                If contra1.Text <> "" Then
                    EditaUsuario.contrasena = contra1.Text
                End If
                EditaUsuario.profesionId = cboprofesiones.SelectedValue
                EditaUsuario.dptCod = cbodepartamentos.SelectedValue
                EditaUsuario.ciudadCod = cbociudad.SelectedValue
                modelo.SubmitChanges()
                limpiarFormulario("E")
            Else
                'Crea el registro
                Clausuarios.usuario = usuario.Text
                Clausuarios.nombre = nombre.Text
                Clausuarios.documento = documento.Text
                Clausuarios.celular = celular.Text
                Clausuarios.contrasena = contra1.Text
                Clausuarios.profesionId = cboprofesiones.SelectedValue
                Clausuarios.dptCod = cbodepartamentos.SelectedValue
                Clausuarios.ciudadCod = cbociudad.SelectedValue
                modelo.usuarios.InsertOnSubmit(Clausuarios)
                modelo.SubmitChanges()
                limpiarFormulario("C")
            End If

        End If
    End Sub

    Private Sub limpiarFormulario(ByVal opc As String)
        GridView1.DataBind()
        If opc = "E" Then
            Label1.Text = "Se modificado correctamente el usuario"
        Else
            Label1.Text = "Se ha creado correctamente el usuario"
        End If
        usuario.Text = ""
        nombre.Text = ""
        documento.Text = ""
        celular.Text = ""
        contra1.Text = ""
        contra2.Text = ""
        btnGuardar.Text = "Guardar"
        cboprofesiones.SelectedIndex = -1
        cbodepartamentos.SelectedIndex = -1
        cbociudad.Items.Clear()
        usuarioId.Value = ""
    End Sub

    Private Sub limpiar()
        cbociudad.Items.Clear()
        cbodepartamentos.SelectedIndex = -1
        GridView1.DataBind()
    End Sub
    Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        Try
            Select Case e.Row.RowType
                Case DataControlRowType.DataRow
                    Dim ctrlEliminar As ImageButton = CType(e.Row.Cells(1).Controls(0), ImageButton)
                    ctrlEliminar.OnClientClick = "if(!confirm('¿Esta seguro de eliminar este funcionario?')){return;}"
                    ctrlEliminar.ToolTip = "Eliminar"
                    'Dim ctrlSelect As ImageButton = CType(e.Row.Cells(1).Controls(0), ImageButton)
                    'ctrlSelect.ToolTip = "Seleccionar"
            End Select
        Catch ex As Exception
            'Response.Write(ex.Message)
        End Try
    End Sub
    Protected Sub GridView1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles GridView1.SelectedIndexChanged
        Try
            Dim row As GridViewRow = GridView1.SelectedRow
            usuario.Text = row.Cells(3).Text
            documento.Text = row.Cells(4).Text
            nombre.Text = row.Cells(5).Text
            celular.Text = row.Cells(6).Text
            cboprofesiones.SelectedValue = cboprofesiones.Items.FindByText(row.Cells(7).Text).Value
            cbodepartamentos.SelectedValue = cbodepartamentos.Items.FindByText(row.Cells(9).Text).Value
            cbodepartamentos_SelectedIndexChanged(sender, e)
            cbociudad.SelectedValue = cbociudad.Items.FindByText(row.Cells(8).Text).Value
            usuarioId.Value = row.Cells(2).Text
            'btnGuardar.
            btnGuardar.Text = "Editar"
        Catch ex As Exception
            Label1.Text = ex.Message
        End Try

    End Sub
    Protected Sub btnBusRapida_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnBusRapida.Click
        SqlDataSource2.FilterExpression = geriatriaClases.fnbusquedaRapida(txtBusquedaRapida.Text.ToString())
        SqlDataSource2.DataBind()
    End Sub
    Protected Sub btnConsulta_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnConsulta.Click
        Dim where As String
        where = " 1 = 1"
        If cbotipDocumento.SelectedValue.Trim <> "-1" Then
            where = where + " and tipoDocumento = '" + cbotipDocumento.SelectedValue.Trim + "'"
        End If
        If txtDocumento.Text.Trim <> "" Then
            where = where + " and documento = '" + txtDocumento.Text.Trim + "'"
        End If
        If conPrinombre.Text.Trim <> "" Then
            where = where + " and primerNombre like '%" + conPrinombre.Text.Trim + "%'"
        End If
        If conSegnombre.Text.Trim <> "" Then
            where = where + " and segundoNombre like '%" + conSegnombre.Text.Trim + "%'"
        End If
        If conPriApe.Text.Trim <> "" Then
            where = where + " and primerApellido like '%" + conPriApe.Text.Trim + "%'"
        End If
        If conSegApe.Text.Trim <> "" Then
            where = where + " and segundoApellido like '%" + conSegApe.Text.Trim + "%'"
        End If
        SqlDataSource2.FilterExpression = where
        SqlDataSource2.DataBind()
    End Sub

    Protected Sub btnExportarBDGeriatria_Click(sender As Object, e As EventArgs) Handles btnExportarBDGeriatria.Click
        Dim fechIni As String = "geri.fechaCreo as Fecha_Medición"
        Dim muestra As String = ",usua.nombre as UsuarioCreo,geri.*"
        Dim baseAux As String = "inner join medicoGeriatra as geri on geri.participantesId = par.participanteId inner join usuarios as usua on usua.usuarioId = geri.usuario_Id"
        Dim nombre As String = "GERIATRIA_BD"
        Export(fechIni, muestra, baseAux, nombre)
    End Sub
    Protected Sub Export(fechMedicion As String, muestra As String, baseAux As String, nombreExport As String)
        Try
            Dim sqlMuestra As String = "select " & fechMedicion & ",par.*,socio.*"
            Dim sqlBase As String = " from participantes as par inner join socioeconomico as socio on socio.participanteId = par.participanteId "
            Dim sb As StringBuilder = New StringBuilder()
            Dim sw As System.IO.StringWriter = New System.IO.StringWriter(sb)
            Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
            Dim pagina As Page = New Page
            Dim form = New HtmlForm
            Dim Docmd As New DoCmd
            Dim GridView2 As New GridView
            Docmd.Conectar()
            Dim dr As Data.SqlClient.SqlDataReader = Docmd.Read_SQL(sqlMuestra & muestra & sqlBase & baseAux)
            If dr.HasRows Then
                GridView2.HeaderStyle.Font.Bold = True
                GridView2.EnableViewState = False
                GridView2.DataSource = dr
                GridView2.DataBind()
                Docmd.Desconectar()
                pagina.EnableEventValidation = False
                pagina.DesignerInitialize()
                pagina.Controls.Add(form)
                form.Controls.Add(GridView2)
                pagina.RenderControl(htw)
                Response.Clear()
                Response.Buffer = True
                Response.ContentType = "application/vnd.ms-excel"
                Response.AddHeader("Content-Disposition", "attachment;filename=" & nombreExport & ".xls")
                Response.Charset = "UTF-8"
                Response.ContentEncoding = Encoding.Default
                Response.Write(sb.ToString())
                Response.End()
            Else
                Docmd.Desconectar()
                Msgbox_Web.CreateMessageAlertInUpdatePanel(UpdatePanel2, "alert('No hay registros para exportar');fnReportesBD();")
            End If
        Catch ex As Exception
            'LblMensaje.Text = ex.Message
        End Try
    End Sub

    Protected Sub btnExportarBDTerapia_Click(sender As Object, e As EventArgs) Handles btnExportarBDTerapia.Click
        Dim fechIni As String = "geri.fechaCreo as Fecha_Medición"
        Dim muestra As String = ",usua.nombre as UsuarioCreo,geri.*"
        Dim baseAux As String = "inner join terapiaOcupacional as geri on geri.participantesId = par.participanteId inner join usuarios as usua on usua.usuarioId = geri.usuario_Id"
        Dim nombre As String = "TERAPIA_OCUPACIONAL_BD"
        Export(fechIni, muestra, baseAux, nombre)
    End Sub

    Protected Sub btnExportarBDDinamiza_Click(sender As Object, e As EventArgs) Handles btnExportarBDDinamiza.Click
        Dim fechIni As String = "socio.fechaCreo as Fecha_Medición"
        Dim muestra As String = ",usua.nombre as UsuarioCreo"
        Dim baseAux As String = "inner join usuarios as usua on usua.usuarioId = socio.usuario_Id"
        Dim nombre As String = "DINAMIZADOR_BD"
        Export(fechIni, muestra, baseAux, nombre)
    End Sub
    Protected Sub btnExportarBDSico_Click(sender As Object, e As EventArgs) Handles btnExportarBDSico.Click
        Dim fechIni As String = "geri.fechaCreo as Fecha_Medición"
        Dim muestra As String = ",usua.nombre as UsuarioCreo,geri.*"
        Dim baseAux As String = "inner join psicosocial as geri on geri.participantesId = par.participanteId inner join usuarios as usua on usua.usuarioId = geri.usuario_Id"
        Dim nombre As String = "PSICOLOGIA_BD"
        Export(fechIni, muestra, baseAux, nombre)
    End Sub
    Protected Sub btnExportarBDNutri_Click(sender As Object, e As EventArgs) Handles btnExportarBDNutri.Click
        Dim fechIni As String = "geri.fechaCreo as Fecha_Medición"
        Dim muestra As String = ",usua.nombre as UsuarioCreo,geri.*"
        Dim baseAux As String = "inner join nutricion as geri on geri.participantesId = par.participanteId inner join usuarios as usua on usua.usuarioId = geri.usuario_Id"
        Dim nombre As String = "NUTRICION_BD"
        Export(fechIni, muestra, baseAux, nombre)
    End Sub
    Protected Sub btnExportarBDFisio_Click(sender As Object, e As EventArgs) Handles btnExportarBDFisio.Click
        Dim fechIni As String = "geri.fechaCreo as Fecha_Medición"
        Dim muestra As String = ",usua.nombre as UsuarioCreo,geri.*"
        Dim baseAux As String = "inner join fisioterapia as geri on geri.participantesId = par.participanteId inner join usuarios as usua on usua.usuarioId = geri.usuario_Id"
        Dim nombre As String = "FISIOTERAPIA_BD"
        Export(fechIni, muestra, baseAux, nombre)
    End Sub
End Class